#!/usr/bin/env bash

#########################################################################
# Which Interpreter handle this script?
readonly INTERPRETER="$(readlink -fn "/proc/$$/exe")"

if [[ ! "bash" == "$(basename "${INTERPRETER}")" ]]; then
  echo "Interpreter \"${INTERPRETER}\" is not \"bash\"!"
  exit 1
fi

#########################################################################
# Script's location without symlink
readonly PWD0="$(dirname "$(readlink -fn "${BASH_SOURCE[0]}")")"

#########################################################################
function main() {
  readonly IMG_NAME="air/build-env"
  declare launch_command
  echo "===================================================="
  echo -n ">>>> Finding image builder ... "
  if command -v podman; then
    declare -r CMD="podman"
    launch_command="
      exec bash
    "
  elif command -v docker; then
    declare -r CMD="docker"
    launch_command="
      useradd -m -u $(id -u) $(id -un)
      echo $(id -un) ALL=\(ALL\) NOPASSWD: ALL >> /etc/sudoers
      su $(id -un) -s /bin/bash
    "
  else
    echo "Neither podman nor docker existed!"
    exit 1
  fi
  echo "===================================================="
  declare img_tag
  img_tag=$(
    ${CMD} images | grep "${IMG_NAME}" |
      sort -r |
      head -n1 |
      awk '{print $2}'
  )
  if [[ "x${img_tag}" == "x" ]]; then
    echo "Cannot find image tag. Please run build-env-create.bash first."
    exit 1
  fi
  declare code_path
  declare code_name
  code_path="$(dirname "${PWD0}")"
  code_name="$(basename "${code_path}")"
  echo "===================================================="
  echo "All changes without in /opt/${code_name} will be lost! "
  echo "All changes without in /opt/${code_name} will be lost! "
  echo "All changes without in /opt/${code_name} will be lost! "
  echo "===================================================="
  exec ${CMD} run --rm \
    -v "${code_path}:/opt/${code_name}:Z" \
    -it "${IMG_NAME}:${img_tag}" \
    bash -c "
      cd /opt/${code_name}
      ${launch_command}
    "
}
main
